<template>
  <div class="favorites-page">
    <!-- Header -->
    <van-nav-bar 
      title="Favorites" 
      left-text="Back" 
      left-arrow 
      @click-left="$router.back()"
      fixed 
      placeholder
    />

    <!-- Filter Tabs -->
    <van-tabs v-model="activeTab" @change="onTabChange" sticky>
      <van-tab title="Characters" name="characters">
        <div class="favorites-content">
          <div v-if="favoriteCharacters.length > 0" class="characters-list">
            <div 
              class="character-card" 
              v-for="character in favoriteCharacters" 
              :key="character.id"
              @click="selectCharacter(character)"
            >
              <div class="character-avatar">
                <van-image
                  :src="character.avatar"
                  width="60"
                  height="60"
                  round
                  fit="cover"
                />
                <van-icon 
                  name="star" 
                  class="favorite-icon active"
                  @click.stop="toggleFavorite(character, 'character')"
                />
              </div>
              <div class="character-info">
                <div class="character-name">{{ character.name }}</div>
                <div class="character-description">{{ character.description }}</div>
                <div class="character-tags">
                  <van-tag 
                    v-for="tag in character.specialties.slice(0, 2)" 
                    :key="tag" 
 
                    type="primary"
                  >
                    {{ tag }}
                  </van-tag>
                </div>
                <div class="character-stats">
                  <div class="stat">
                    <van-icon name="star-o" size="12" />
                    <span>{{ character.rating.toFixed(1) }}</span>
                  </div>
                  <div class="stat">
                    <van-icon name="user-o" size="12" />
                    <span>{{ character.totalSessions }}</span>
                  </div>
                  <div class="difficulty-badge" :class="character.difficulty">
                    {{ character.difficulty }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <van-empty v-else description="No favorite characters yet">
            <van-button type="primary" @click="goToTraining">
              Explore Characters
            </van-button>
          </van-empty>
        </div>
      </van-tab>

      <van-tab title="Scenarios" name="scenarios">
        <div class="favorites-content">
          <div v-if="favoriteScenarios.length > 0" class="scenarios-list">
            <div 
              class="scenario-card" 
              v-for="scenario in favoriteScenarios" 
              :key="scenario.id"
              @click="selectScenario(scenario)"
            >
              <div class="scenario-thumbnail">
                <van-image
                  :src="scenario.thumbnail"
                  width="80"
                  height="60"
                  fit="cover"
                  radius="8"
                />
                <van-icon 
                  name="star" 
                  class="favorite-icon active"
                  @click.stop="toggleFavorite(scenario, 'scenario')"
                />
              </div>
              <div class="scenario-info">
                <div class="scenario-title">{{ scenario.title }}</div>
                <div class="scenario-description">{{ scenario.description }}</div>
                <div class="scenario-meta">
                  <div class="meta-item">
                    <van-icon name="clock-o" size="12" />
                    <span>{{ scenario.estimatedDuration }}min</span>
                  </div>
                  <div class="meta-item">
                    <van-icon name="star-o" size="12" />
                    <span>{{ scenario.rating.toFixed(1) }}</span>
                  </div>
                  <div class="difficulty-badge" :class="scenario.difficulty">
                    {{ scenario.difficulty }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <van-empty v-else description="No favorite scenarios yet">
            <van-button type="primary" @click="goToTraining">
              Explore Scenarios
            </van-button>
          </van-empty>
        </div>
      </van-tab>

      <van-tab title="Posts" name="posts">
        <div class="favorites-content">
          <div v-if="favoritePosts.length > 0" class="posts-list">
            <div 
              class="post-card" 
              v-for="post in favoritePosts" 
              :key="post.id"
              @click="viewPost(post)"
            >
              <!-- Post Header -->
              <div class="post-header">
                <div class="author-info">
                  <van-image
                    :src="post.author.avatar"
                    width="40"
                    height="40"
                    round
                    fit="cover"
                  />
                  <div class="author-details">
                    <div class="author-name">{{ post.author.username }}</div>
                    <div class="post-time">{{ formatTime(post.createdAt) }}</div>
                  </div>
                </div>
                <van-icon 
                  name="star" 
                  class="favorite-icon active"
                  @click.stop="toggleFavorite(post, 'post')"
                />
              </div>

              <!-- Post Content -->
              <div class="post-content">
                <div class="post-text" v-if="post.content">{{ post.content }}</div>
                <div class="post-images" v-if="post.images && post.images.length > 0">
                  <van-image
                    v-for="(image, index) in post.images.slice(0, 3)"
                    :key="index"
                    :src="image"
                    width="100"
                    height="100"
                    fit="cover"
                    radius="8"
                  />
                </div>
              </div>

              <!-- Post Actions -->
              <div class="post-actions">
                <van-button size="small" icon="good-job-o">
                  {{ post.likesCount }}
                </van-button>
                <van-button size="small" icon="chat-o">
                  {{ post.commentsCount }}
                </van-button>
              </div>
            </div>
          </div>
          
          <van-empty v-else description="No favorite posts yet">
            <van-button type="primary" @click="goToCommunity">
              Explore Community
            </van-button>
          </van-empty>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useTrainingStore } from '@/stores'
import { useCommunityStore } from '@/stores'
import { formatTime } from '@/utils/format'
import type { AICharacter, TrainingScenario, CommunityPost } from '@/types'

const router = useRouter()
const trainingStore = useTrainingStore()
const communityStore = useCommunityStore()

const activeTab = ref('characters')

// Mock favorite data - in real app, this would come from API
const favoriteCharacters = ref<AICharacter[]>([])
const favoriteScenarios = ref<TrainingScenario[]>([])
const favoritePosts = ref<CommunityPost[]>([])

const onTabChange = (name: string) => {
  activeTab.value = name
  loadFavorites(name)
}

const loadFavorites = async (type: string) => {
  try {
    switch (type) {
      case 'characters':
        // TODO: Load favorite characters from API
        // favoriteCharacters.value = await trainingStore.fetchFavoriteCharacters()
        break
      case 'scenarios':
        // TODO: Load favorite scenarios from API
        // favoriteScenarios.value = await trainingStore.fetchFavoriteScenarios()
        break
      case 'posts':
        // TODO: Load favorite posts from API
        // favoritePosts.value = await communityStore.fetchFavoritePosts()
        break
    }
  } catch (error) {
    console.error('Failed to load favorites:', error)
  }
}

const selectCharacter = (character: AICharacter) => {
  router.push(`/training/character/${character.id}`)
}

const selectScenario = (scenario: TrainingScenario) => {
  router.push(`/training/scenario/${scenario.id}`)
}

const viewPost = (post: CommunityPost) => {
  router.push(`/community/post/${post.id}`)
}

const toggleFavorite = async (item: any, type: string) => {
  try {
    switch (type) {
      case 'character':
        await trainingStore.toggleCharacterFavorite(item.id)
        favoriteCharacters.value = favoriteCharacters.value.filter(c => c.id !== item.id)
        break
      case 'scenario':
        await trainingStore.toggleScenarioFavorite(item.id)
        favoriteScenarios.value = favoriteScenarios.value.filter(s => s.id !== item.id)
        break
      case 'post':
        await communityStore.togglePostFavorite(item.id)
        favoritePosts.value = favoritePosts.value.filter(p => p.id !== item.id)
        break
    }
    showToast('Removed from favorites')
  } catch (error) {
    showToast('Failed to update favorite')
  }
}

const goToTraining = () => {
  router.push('/training')
}

const goToCommunity = () => {
  router.push('/community')
}

// Load initial data
onMounted(() => {
  loadFavorites(activeTab.value)
  
  // Mock data for demonstration
  favoriteCharacters.value = [
    {
      id: 1,
      name: 'Emma',
      description: 'Friendly coffee shop regular who loves deep conversations',
      avatar: '/avatars/emma.jpg',
      specialties: ['Small Talk', 'Active Listening'],
      personality: ['Friendly', 'Curious'],
      difficulty: 'beginner' as const,
      rating: 4.8,
      totalSessions: 1250,
      isFavorited: true,
      tags: ['friendly', 'beginner'],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    },
    {
      id: 2,
      name: 'Alex',
      description: 'Professional mentor with years of industry experience',
      avatar: '/avatars/alex.jpg',
      specialties: ['Professional', 'Networking'],
      personality: ['Professional', 'Supportive'],
      difficulty: 'intermediate' as const,
      rating: 4.6,
      totalSessions: 890,
      isFavorited: true,
      tags: ['professional', 'intermediate'],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
  ]

  favoriteScenarios.value = [
    {
      id: 1,
      title: 'Coffee Shop Conversation',
      description: 'Practice casual conversation in a relaxed setting',
      thumbnail: '/scenarios/coffee-shop.jpg',
      difficulty: 'beginner' as const,
      estimatedDuration: 15,
      rating: 4.7,
      category: 'social',
      objectives: ['Break the ice', 'Maintain conversation'],
      skills: ['conversation', 'listening'],
      isPopular: true,
      totalSessions: 1250,
      isFavorited: true,
      tags: ['casual', 'conversation'],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
  ]

  favoritePosts.value = [
    {
      id: 1,
      content: 'Just completed my first training session with Emma! Amazing experience.',
      author: {
        id: 1,
        username: 'SocialLearner',
        avatar: '/avatars/user1.jpg'
      },
      likesCount: 24,
      commentsCount: 8,
      isLiked: false,
      createdAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
    }
  ]
})
</script>

<style lang="scss" scoped>
.favorites-page {
  min-height: 100vh;
  background: $background-color;
}

.favorites-content {
  padding: $spacing-md;
}

.characters-list {
  .character-card {
    background: $white;
    border-radius: $border-radius-lg;
    padding: $spacing-md;
    margin-bottom: $spacing-md;
    display: flex;
    gap: $spacing-md;
    box-shadow: $box-shadow-light;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:active {
      transform: scale(0.98);
    }

    .character-avatar {
      position: relative;

      .favorite-icon {
        position: absolute;
        top: -4px;
        right: -4px;
        background: $white;
        border-radius: 50%;
        padding: 4px;
        color: $warning-color;
        box-shadow: $box-shadow-light;
        cursor: pointer;

        &.active {
          color: $warning-color;
        }
      }
    }

    .character-info {
      flex: 1;

      .character-name {
        font-size: $font-size-md;
        font-weight: $font-weight-medium;
        color: $text-color;
        margin-bottom: $spacing-xs;
      }

      .character-description {
        font-size: $font-size-sm;
        color: $text-color-3;
        margin-bottom: $spacing-sm;
        line-height: 1.4;
      }

      .character-tags {
        margin-bottom: $spacing-sm;
        display: flex;
        gap: $spacing-xs;
      }

      .character-stats {
        display: flex;
        align-items: center;
        gap: $spacing-md;

        .stat {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: $font-size-xs;
          color: $text-color-3;
        }

        .difficulty-badge {
          font-size: $font-size-xs;
          padding: 2px 6px;
          border-radius: 4px;
          font-weight: $font-weight-medium;

          &.beginner {
            background: #e8f5e8;
            color: #52c41a;
          }

          &.intermediate {
            background: #fff7e6;
            color: #fa8c16;
          }

          &.advanced {
            background: #fff2f0;
            color: #f5222d;
          }
        }
      }
    }
  }
}

.scenarios-list {
  .scenario-card {
    background: $white;
    border-radius: $border-radius-lg;
    padding: $spacing-md;
    margin-bottom: $spacing-md;
    display: flex;
    gap: $spacing-md;
    box-shadow: $box-shadow-light;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:active {
      transform: scale(0.98);
    }

    .scenario-thumbnail {
      position: relative;

      .favorite-icon {
        position: absolute;
        top: -4px;
        right: -4px;
        background: $white;
        border-radius: 50%;
        padding: 4px;
        color: $warning-color;
        box-shadow: $box-shadow-light;
        cursor: pointer;
      }
    }

    .scenario-info {
      flex: 1;

      .scenario-title {
        font-size: $font-size-md;
        font-weight: $font-weight-medium;
        color: $text-color;
        margin-bottom: $spacing-xs;
      }

      .scenario-description {
        font-size: $font-size-sm;
        color: $text-color-3;
        margin-bottom: $spacing-sm;
        line-height: 1.4;
      }

      .scenario-meta {
        display: flex;
        align-items: center;
        gap: $spacing-md;

        .meta-item {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: $font-size-xs;
          color: $text-color-3;
        }
      }
    }
  }
}

.posts-list {
  .post-card {
    background: $white;
    border-radius: $border-radius-lg;
    margin-bottom: $spacing-md;
    box-shadow: $box-shadow-light;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:active {
      transform: scale(0.98);
    }

    .post-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: $spacing-md;
      border-bottom: 1px solid $border-color-light;

      .author-info {
        display: flex;
        align-items: center;
        gap: $spacing-sm;

        .author-details {
          .author-name {
            font-size: $font-size-sm;
            font-weight: $font-weight-medium;
            color: $text-color;
          }

          .post-time {
            font-size: $font-size-xs;
            color: $text-color-3;
          }
        }
      }

      .favorite-icon {
        color: $warning-color;
        cursor: pointer;
      }
    }

    .post-content {
      padding: $spacing-md;

      .post-text {
        font-size: $font-size-sm;
        color: $text-color-2;
        line-height: 1.5;
        margin-bottom: $spacing-sm;
      }

      .post-images {
        display: flex;
        gap: $spacing-xs;
        margin-bottom: $spacing-sm;
      }
    }

    .post-actions {
      display: flex;
      gap: $spacing-md;
      padding: $spacing-sm $spacing-md;
      border-top: 1px solid $border-color-light;
    }
  }
}
</style>